package com.sketch.commom.utils;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class JwtUtil {

	public final static String JWT_SECRET = "asdasdasifhrfewbfjsdafjkueuiwyu";


	public static String createJWT(String session, long ttlMillis) {
		//The JWT signature algorithm we will be using to sign the token
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);

		//We will sign our JWT with our ApiKey secret
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(JWT_SECRET);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

		//Let's set the JWT Claims
		JwtBuilder builder = Jwts.builder()
				.setIssuedAt(now)
				.claim("session", session)
				.signWith(signatureAlgorithm, signingKey);
		//if it has been specified, let's add the expiration
		if (ttlMillis >= 0) {
			long expMillis = nowMillis + ttlMillis;
			Date exp = new Date(expMillis);
			builder.setExpiration(exp);
		}
		//Builds the JWT and serializes it to a compact, URL-safe string
		return builder.compact();
	}

	public static Long verfiyToken(String token) {
		Jws<Claims> claims;
		try {
			claims = Jwts.parser()
					.setSigningKey(JWT_SECRET)
					.parseClaimsJws(token);
		} catch (ExpiredJwtException e) {
			//token过期
			return 0L;
		} catch (Exception e) {
			//token异常
			return -1L;
		}
		return claims.getBody().getExpiration().getTime() - System.currentTimeMillis();
	}

	public static String getSession(String token) {
		if (StringUtils.isEmpty(token)) {
			return null;
		}
		Jws<Claims> claims;
		try {
			claims = Jwts.parser()
					.setSigningKey(JWT_SECRET)
					.parseClaimsJws(token);
		} catch (Exception e) {
			//token过期
			return null;
		}
		return claims.getBody().get("session", String.class);
	}
}
